package com.jchz.net.comhttp.callback;

import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public abstract class StringCallBack extends BaseCallBack<String> {

    @Override
    public void onNext(String response) {
        Log.e("StringCallBack", "网络请求成功" + response);

//        if (response.indexOf("[") == 0) {
//            //数据处理
//            response = response.substring(response.indexOf("[") + 1, response.length() - 1);
//        }
        if (!TextUtils.isEmpty(response)) {
            final String finalResponse = response;
            try {
                JSONObject jsonObject = JSON.parseObject(response);
                String state  = jsonObject.getString(Result.STATE);
                if (!TextUtils.isEmpty(state)) {
                    mDelivery.post(new Runnable() {
                        @Override
                        public void run() {
                            onXError(state);
                        }
                    });
                }
            }catch (Exception e){
                mDelivery.post(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("StringCallBack", "解密数据" + finalResponse);
                        onSuccess(finalResponse);
                    }
                });
            }
        } else {
            mDelivery.post(new Runnable() {
                @Override
                public void run() {
                    onXError("没有数据");
                }
            });
        }

    }


    @Override
    public void onError(final Throwable e) {
        mDelivery.post(new Runnable() {
            @Override
            public void run() {
                Log.e("TODO", e.getMessage() + "");
                onXError(e.getMessage());
            }
        });
    }


    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onCompleted() {
    }

    protected abstract void onXError(String exception);


    protected abstract void onSuccess(String response);


}